<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >

      <div class="header">
        <!-- <img src="@/assets/nvbar_logo_white.png"> -->
      </div>

      <div class="title-container">
        <h3 class="title">直播后台管理系统</h3>
      </div>

      <el-form-item prop="username">
        <div class="input-wrap">
          <i class="el-icon-user-solid" />
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="用户名"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </div>

      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <div class="input-wrap">
            <i class="el-icon-s-goods" />
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="密码"
              tabindex="2"
              autocomplete="on"
              show-password
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
          </div>
        </el-form-item>
      </el-tooltip>
      <div class="auth-code-input-box">
        <el-form-item>
          <div class="input-wrap" style="width: 200px;">
            <i class="el-icon-s-help" />
            <el-input
              ref="authCode"
              v-model="loginForm.authCode"
              placeholder="验证码"
              name="验证码"
              type="text"
              autocomplete="on"
            />
          </div>
        </el-form-item>

        <img
          loading="eager"
          :src="authCodeImg"
          height="55px"
          width="70px"
          style="cursor:pointer; margin-left: 10px;"
          @click="initAuthCode"
        >
      </div>

      <el-button
        :loading="loading"
        type="warning"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
      >登 录</el-button>

    </el-form>

  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'
import { getSessionID, getAuthCode } from '@/api/user'

export default {
  name: 'Login',
  // eslint-disable-next-line vue/no-unused-components
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入合法用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 8) {
        callback(new Error('密码不能小于8位'))
      } else {
        callback()
      }
    }
    const validateAuthCode = (rule, value, callback) => {
      if (value.length !== 4) {
        callback(new Error('请输入有效验证码'))
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        authCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        authCode: [{ require: true, trigger: blur, validator: validateAuthCode }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      authCodeImg: '',
      sessionID: ''

    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    } else if (this.loginForm.authCode === '') {
      this.$refs.authCode.focus()
    }
    this.initAuthCode()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        // base64 encode
        var encryptPassword = window.btoa(this.loginForm.password)
        const reqData = {
          AuthCode: this.loginForm.authCode,
          SessionId: this.sessionID,
          UserName: this.loginForm.username,
          password: encryptPassword,
          way: 'password'
        }
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', reqData)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    async initAuthCode() {
      const sessionInfo = await getSessionID()
      this.sessionID = sessionInfo.data.SessionId
      if (this.sessionID === undefined || this.sessionID === ``) {
        console.log('error sessionID', this.sessionID)
      }
      const reqParmas = {
        SessionId: this.sessionID
      }
      const authCodeInfo = await getAuthCode(reqParmas)
      this.authCodeImg = `data:image/png;base64,` + authCodeInfo.data.img
      if (this.authCodeImg === undefined || this.authCodeImg === ``) {
        console.log('error authCodeImg', this.authCodeImg)
      }
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor  !important;
      }
    }
  }

  .el-form-item {
    margin-bottom: 41px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

@media screen and (min-width:900px) {
  .login-container {
    .login-form {
      position: absolute !important;
      top: calc(50% - 326px);
      right: 108px;
      border-radius: 6px;

      .el-form-item {
        background-color: #fff;
        border-bottom-color: $bg;
        border-radius: 0;
      }
    }
  }

}

::v-deep input {
  color: $bg  !important;
  caret-color: $bg  !important;
  font-size: 24px !important;
}

.login-container .el-input ::v-deep input:-webkit-autofill {
  box-shadow: 0 0 0px 1000px #fff inset !important;
  color: $bg  !important;
  -webkit-text-fill-color: $bg  !important;
  font-size: 24px !important;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  background: url(../../assets/login-background.png) no-repeat;
  background-size: 100;

  .login-form {
    position: relative;
    width: 492px;
    height: 651px;
    padding: 36px 50px 71px;
    margin: 0 auto;
    background-color: rgba($color: #000, $alpha: 0.35);
    transform: scale(0.85);

    .header {
      width: 179px;
      height: 57px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .authCode-container {
    // padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 15px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    margin: 51px 0 29px;

    .title {
      font-size: 30.66px;
      line-height: 30.66px;
      color: #fff;
      font-weight: Regular;
    }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}

.auth-code-input-box {
  display: flex;
  flex-wrap: nowrap;
  margin-right: 20px;
}

::v-deep .el-input__icon,
.el-icon-view,
.el-input__clear {
  line-height: 50px !important;
}

::v-deep .el-button {
  margin-top: 28px;
  width: 393px;
  height: 55px;
  border-radius: 7px;
  background-color: #FF9600;
  border-color: #FF9600;
  font-size: 18px;
  font-weight: Regular;
}

.el-icon-s-help,
.el-icon-s-goods,
.el-icon-user-solid {
  font-size: 25px;
  color: #5F6165;
}

.input-wrap {
  padding-left: 18px;
  width: 100%;
  height: 55px;
  display: flex;
  align-items: center;
  overflow: hidden;
}

::v-deep .el-form-item__error {
  font-size: 20px !important;
}
::v-deep .el-icon-view,.el-input__clear {
  font-size: 24px !important;
}
</style>
